<template>
    <div class="flex_col p10 card m5">
        <label class="flex_center_self">串口设置</label>
        <div class="flex_row_center mt5">
            <label>端口</label>
            <el-select v-model="selectPort" class="sp_select ml5">
                <el-option v-for="(item, index) in ports" :key="index" :label="item" :value="item" />
            </el-select>
            <el-button @click="update" class="ml5">刷新</el-button>
        </div>
        <div class="flex_row_center mt5">
            <el-button @click="onClickOpen" type="primary">{{ openText }}</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">

import { availablePorts, open, isOpen, close } from "../service/serial_port";
import { ref } from 'vue';
import { ElMessage } from 'element-plus';

const ports = ref<string[]>([]);
const selectPort = ref('');
const openText = ref('打开');

async function update() {
    ports.value = await availablePorts();
    if (ports.value.length != 0) {
        selectPort.value = ports.value[0];
    }
}

async function onClickOpen() {

    if (await isOpen()) {
        await close();
        ElMessage({
            message: '关闭成功',
            type: 'success',
        })
    } else {
        try {
            const port = selectPort.value;
            if (port.length == 0) {
                throw '没有串口'
            }
            await open(port);
            ElMessage({
                message: '打开成功',
                type: 'success'
            })
        } catch (e) {
            console.log(e);
            ElMessage({
                message: e as string,
                type: 'error',
            });
        }
    }

    await updateStatus();
}

async function updateStatus() {
    const ret = await isOpen();
    if (ret) {
        openText.value = '关闭';
    } else {
        openText.value = '打开';
    }
}

updateStatus();
update();

</script>

<style scoped>
.sp_select {
    width: 120px;
}
</style>

